package com.yisu.expressway.customService;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;

/**
 * Created by MIGU on 2016/12/5.
 */

public class TTSPlayer {
    private static final String voicer = "xiaoyan";
    private static final String TAG = "ttsplayer";

    private static SpeechSynthesizer mTts;
    private static TTSPlayer mInstance;
    private static boolean mInitialized = false;

    private TTSPlayer() {

    }

    public static TTSPlayer getmInstance() {
        if (mInstance == null) {
            mInstance = new TTSPlayer();
        }
        return mInstance;
    }

    private static InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {

            } else {
            }
        }
    };

    public static void init(Context ctx) {
        if (!mInitialized) {
            mTts = SpeechSynthesizer.createSynthesizer(ctx, mTtsInitListener);
            setParam();
            mInitialized = true;
        }
    }

    private static void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置在线合成发音人
        mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
        //设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, "50");
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        //设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME, "50");
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    public void destroy() {
        if (mTts != null) {
            mTts.stopSpeaking();
            mTts.destroy();
        }
    }

    public void playText(String text) {
        if (mTts != null && text != null) {
            mTts.startSpeaking(text, null);
        }
    }
}
